<template>
  <div class="company-container">
    <div class="top">
      <el-row type="flex" justify="left">
        <div class="top_item">
          <label class="label">企业名称</label>
          <el-input v-model="partCompany" type="text" placeholder="请输入企业名称" class="input" clearable />
        </div>
        <div class="top_item">
          <el-button type="primary" icon="el-icon-search" @click="getListInfo()">查询</el-button>
          <el-button @click="reset()"> 重置</el-button>
        </div>
        <div class="top_item_right">
          <el-button type="primary" icon="el-icon-plus" @click="openSaveCompanyDialog()">新增</el-button>
          <el-button icon="el-icon-upload2" @click="openUploadDialog()">批量导入</el-button>
        </div>
        <el-dialog title="新增企业信息" :visible.sync="showAddCompanyDialog" custom-class="customWidth">
          <el-row type="flex" justify="center" class="addCompany">
            <label>企业名称</label>
            <el-input v-model="companyName" type="text" placeholder="请输入企业名称" clearable />
          </el-row>
          <el-row type="flex" justify="center" class="addCompany">
            <label>统一信用代码</label>
            <el-input v-model="creditCode" type="text" placeholder="请输入统一信用代码" clearable />
          </el-row>
          <el-row type="flex" justify="center">
            <el-button type="primary" @click="saveCompany()">确定</el-button>
            <el-button @click="resetAdd()"> 重置</el-button>
          </el-row>
        </el-dialog>
        <el-dialog title="批量上传企业信息" :visible.sync="showUploadDialog" custom-class="customWidth">
          <el-row type="flex" justify="center">
            <el-upload
              name="companyList"
              drag
              action="http://111.229.91.66:8082/company/batchSaveCompany"
              :on-error="handleError"
              :on-success="handleSuccess"
              :multiple="false"
            >
              <i class="el-icon-upload" />
              <div class="el-upload__text"><center>将excel文件拖到此处，或<em>点击上传</em></center></div>
              <div slot="tip" class="el-upload__tip"><center>只能上传xls/xlsx文件，且不超过500kb</center></div>
            </el-upload>
          </el-row>
          <el-row type="flex" justify="center" style="margin-top: 50px">
            <span style="cursor:pointer" @click="download1()"><center>模板下载</center></span>
          </el-row>
        </el-dialog>
      </el-row>
      <el-row type="flex" justify="left">
        <el-table
          :header-cell-style="{'text-align':'center'}"
          :cell-style="{'text-align':'center'}"
          max-height="400px"
          :data="companyInfoData"
        >
          <el-table-column v-if="false" prop="companyId" label="编号" />
          <el-table-column prop="" label="序号" :formatter="handleIndex" />
          <el-table-column prop="companyName" label="企业名称" />
          <el-table-column prop="companyCreditCode" label="统一信用代码" />
          <el-table-column label="操作" fixed="right" min-width="120px">
            <template slot-scope="scope">
              <el-button type="primary" size="small" @click="showModifyDialog(scope.row)">修改</el-button>&nbsp;
              <!-- <el-button size="small">删除</el-button>&nbsp; -->
            </template>
          </el-table-column>
        </el-table>
      </el-row>
      <el-dialog v-if="companyInfo!= null" title="修改企业信息" :visible.sync="modifyCompanyDialog" custom-class="customWidth">
        <el-row type="flex" justify="center" class="addCompany">
          <label>企业名称</label>
          <el-input v-model="modifyCompanyName" type="text" placeholder="请输入企业名称" clearable />
        </el-row>
        <el-row type="flex" justify="center" class="addCompany">
          <label>统一信用代码</label>
          <el-input v-model="modifyCompanyCreditCode" type="text" placeholder="请输入统一信用代码" clearable />
        </el-row>
        <el-row type="flex" justify="center">
          <el-button type="primary" @click="saveModifyCompany()">确定</el-button>
          <el-button @click="resetMofidy()"> 重置</el-button>
        </el-row>
      </el-dialog>
      <el-row type="flex" justify="left" class="pagination">
        <el-pagination
          :page-size="pageSize"
          :current-page="currentPage"
          :page-sizes="[5,10,20,50]"
          layout="sizes,prev,pager,next,total"
          :total="totalCount"
          @size-change="handleCompanyInfoSizechange"
          @current-change="handleCompanyInfoCurrentchange"
        />
      </el-row>
    </div>
  </div>
</template>
<script>
import compApi from '@/api/compApi.js'
import store from '@/store'
import { MessageBox } from 'element-ui'
import { getUserInfo } from '@/api/user.js'
import router from '@/router'
import { getToken } from '@/utils/auth'
export default {
  name: 'Lalala',
  data() {
    // 保证每个实例都初始化一次
    return {
      ind: 1,
      partCompany: '',
      companyName: '',
      creditCode: '',
      showAddCompanyDialog: false,
      showUploadDialog: false,
      companyInfoData: [],
      pageSize: 5,
      totalCount: 0,
      currentPage: 1,
      modifyCompanyDialog: false,
      companyInfo: null,
      modifyCompanyId: '',
      modifyCompanyName: '',
      modifyCompanyCreditCode: ''
    }
  },
  // 加载页面时执行
  created() {
    this.getListInfo()
  },
  // 方法区
  methods: {
    download1: function() {
      compApi.downloadFile().then(res => {
        if (res.retCode == null || res.retCode === '0000') {
          console.log(res)
          var date = new Date()
          var ele = document.createElement('a')// 创建下载链接
          ele.download = 'company' +
          date.getFullYear() + (date.getMonth() + 1) + date.getDate() +
          date.getHours() + date.getMinutes() + date.getSeconds() +
          '.xlsx'// 设置下载的名称
          ele.style.display = 'none'// 隐藏的可下载链接
          // 字符内容转变成blob地址
          var blob = new Blob([res])
          ele.href = URL.createObjectURL(blob)
          // 绑定点击时间
          document.body.appendChild(ele)
          ele.click()
          // 然后移除
          document.body.removeChild(ele)
        } else {
          this.$message.error('下载模板失败，原因' + res.retMsg)
        }
      })
    },
    resetAdd: function() {
      this.companyName = ''
      this.creditCode = ''
    },
    resetMofidy: function() {
      this.modifyCompanyId = this.companyInfo.companyId
      this.modifyCompanyName = this.companyInfo.companyName
      this.modifyCompanyCreditCode = this.companyInfo.companyCreditCode
    },
    reset: function() {
      this.partCompany = ''
      this.currentPage = 1
    },
    getListInfo: function() {
      this.currentPage = 1
      this.getCompanyListInfo()
    },
    getCompanyListInfo: function() {
      const params = {
        partCompany: this.partCompany,
        pageSize: this.pageSize,
        currentPage: this.currentPage
      }
      compApi.searchCompanyList(params).then(res => {
        if (res.retCode === '0000') {
          this.companyInfoData = res.list
          this.totalCount = res.pageInfo.totalSize
        } else {
          this.$message.error('获取公司列表信息失败，原因' + res.retMsg)
        }
      })
    },
    openSaveCompanyDialog: function() {
      getUserInfo().then(res => {
        if (res.userId === 'guest' || !getToken()) {
          MessageBox.alert('用户登录已过期，请重新登录', '提示', {
            confirmButtonText: '确定',
            callback: action => {
              store.dispatch('user/logout').then(() => {
                router.push('/login')
              })
            }
          })
        } else {
          this.showAddCompanyDialog = true
        }
      })
    },
    saveModifyCompany: function() {
      const params = {
        companyId: this.modifyCompanyId,
        companyName: this.modifyCompanyName,
        companyCreditCode: this.modifyCompanyCreditCode
      }
      compApi.updateCompany(params).then(res => {
        if (res.retCode === '0000') {
          this.$message.success('修改公司信息成功' + res.retMsg)
          this.resetAdd()
          this.modifyCompanyDialog = false
          this.companyInfo = null
          this.modifyCompanyId = ''
          this.modifyCompanyName = ''
          this.modifyCompanyCreditCode = ''
          this.getCompanyListInfo()
        } else {
          this.$message.error('保存公司信息失败，原因' + res.retMsg)
          this.getCompanyListInfo()
        }
      })
    },
    saveCompany: function() {
      const params = {
        companyName: this.companyName,
        companyCreditCode: this.creditCode
      }
      compApi.saveCompany(params).then(res => {
        if (res.retCode === '0000') {
          this.$message.success('保存公司信息成功' + res.retMsg)
          this.resetAdd()
          this.showAddCompanyDialog = false
          this.getCompanyListInfo()
        } else {
          this.$message.error('保存公司信息失败，原因' + res.retMsg)
        }
      })
    },
    showModifyDialog: function(companyInfo) {
      getUserInfo().then(res => {
        if (res.userId === 'guest' || !getToken()) {
          MessageBox.alert('用户登录已过期，请重新登录', '提示', {
            confirmButtonText: '确定',
            callback: action => {
              store.dispatch('user/logout').then(() => {
                router.push('/login')
              })
            }
          })
        } else {
          this.modifyCompanyDialog = true
          this.companyInfo = companyInfo
          this.modifyCompanyId = companyInfo.companyId
          this.modifyCompanyName = companyInfo.companyName
          this.modifyCompanyCreditCode = companyInfo.companyCreditCode
        }
      })
    },
    modifyCompanyInfo: function() {
    },
    openUploadDialog: function() {
      getUserInfo().then(res => {
        if (res.userId === 'guest' || !getToken()) {
          MessageBox.alert('用户登录已过期，请重新登录', '提示', {
            confirmButtonText: '确定',
            callback: action => {
              store.dispatch('user/logout').then(() => {
                router.push('/login')
              })
            }
          })
        } else {
          this.showUploadDialog = true
        }
      })
    },
    handleIndex: function(row, column, cellValue, index) {
      return (index + 1) + (this.currentPage - 1) * this.pageSize
    },
    handleCompanyInfoSizechange: function(val) {
      this.pageSize = val
      this.currentPage = 1
      this.getCompanyListInfo()
    },
    handleCompanyInfoCurrentchange: function(val) {
      this.currentPage = val
      this.getCompanyListInfo()
    },
    handleError: function(error, file, fileList) {
      console.log(error)
      this.$message.error('导入失败，原因是:  ' + error.message)
    },
    handleSuccess: function(response, file, fileList) {
      console.log(response)
      if (response.retCode === '0000') {
        this.$message.success('导入成功条数为' + response.successNb + '条，导入失败条数为' + response.failureNb + '条')
        this.getListInfo()
      } else {
        this.$message.error('导入失败, 原因为' + response.retMsg)
      }
    }
  }
}
</script>
<style>
   /* 顶部条件筛选栏*/
  .top {
    margin-top: 10px;
    margin-bottom: 10px;
    padding-top: 20px;
    padding-bottom: 20px;
    width: 100%;
    border:1px solid  rgba(0,0,0,0.2);
    box-shadow:1px 1px 2px 0px rgba(0,0,0,0.2);
  }
  .top_item {
    width: auto;
    display: flex;
    justify-content: center;
    align-items: center;
    margin-left: 10px;
  }
  .top_item_right {
     position: absolute;
     right: 2%;
  }
  .top_item label {
    width: auto;
    min-width: fit-content;
    margin:10px;
  }
  .top_item input {
    width: auto;
    min-width: fit-content;
  }
  .body{
    margin-bottom: 10px;
    padding-top: 20px;
    padding-bottom: 20px;
    width: 100%;
    border: 1px solid  rgba(0,0,0,0.2);
    text-align:center;
    box-shadow:0px 1px 2px 0px rgba(0,0,0,0.2);
   }

  .pagination{
    display: flex;
    justify-content: center;
   }
   .addCompany {
    width: 100%;
    display: flex;
    justify-content: center;
    align-items: center;
    margin-bottom: 2%;
   }
   .addCompany label{
    width: 150px;
    left: 5%;
   }
   .customWidth {
    left: 0px;
    right: 0px;
    margin: 0px auto;
    max-height: 80%;
    position:fixed;
    overflow-y:auto;
  }
  .el-dialog__headerbtn .el-dialog__close {
      position: fixed;
    }
</style>
<style lang="scss" scoped>
.company {
  &-container {
    margin: 30px;
  }
  &-text {
    font-size: 30px;
    line-height: 46px;
  }
}
</style>
